package com.epam.springtest.service;

import com.epam.springtest.domain.User;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;

import javax.mail.internet.MimeMessage;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

/**
 * @author Mikalai Kisel
 */
public class MailServiceImpl implements MailService{

    private final String programName = "Spring-mvc-test";
    private final String mainUrl = "http://localhost:8080/spring-mvc-test/login";

    private final String mailFrom = "kisel.nikolay@gmail.com";

    private String templateName = "registration.ftl";

    private String russianLocale = "русский";

    private JavaMailSender mailSender;

    @Autowired
    private Configuration configuration;

    public void setMailSender(JavaMailSender mailSender) {
        this.mailSender = mailSender;
    }

    @Override
    public void sendEmail(final User user, final Locale locale) {
        MimeMessagePreparator preparator = new MimeMessagePreparator() {
            @Override
            public void prepare(MimeMessage mimeMessage) throws Exception {
                MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
                message.setTo(user.getEmail());
                message.setFrom(mailFrom);

                Map<String, String> model = new HashMap();
                model.put("name", user.getName());
                model.put("program", programName);
                model.put("url", mainUrl);
                model.put("email", user.getEmail());
                model.put("password", user.getPassword());

                configuration.setOutputEncoding("UTF-8");
                if (locale.getDisplayName().equalsIgnoreCase(russianLocale))
                    templateName = "registrationRU.ftl";
                else
                    templateName = "registration.ftl";
                Template template = configuration.getTemplate(templateName);
                Writer out = new StringWriter();
                template.process(model, out);
                message.setText(out.toString());
            }
        };
        mailSender.send(preparator);

    }
}
